openerp.dftg_ext = function(instance) {
    var QWeb = instance.web.qweb,
        _t = instance.web._t;

    instance.web.dftg_ext = instance.web.dftg_ext || {};

    instance.web.views.add('tree_purchase_need', 'instance.web.dftg_ext.NeedListView');
    instance.web.dftg_ext.NeedListView = instance.web.ListView.extend({
        init: function() {
            var self = this;
            this._super.apply(this, arguments);
            this.on('list_view_loaded', this, function() {
                if(self.__parentedParent.$el.find('.oe_purchase_need').length == 0){
                    var button1 = $("<button type='button' class='oe_button oe_purchase_need'>刷新采购需求</button>")
                        .click(this.proxy('do_refresh_action'));
                    self.__parentedParent.$el.find('.oe_list_buttons').append(button1);
                }
            });
        },
        do_refresh_action: function () {
            var self = this;
            var action_manager = new instance.web.ActionManager(self);
            var context = this.ViewManager.action.context;
            var pnrw_obj = new instance.web.Model('purchase.need.refresh.wizard')
            return pnrw_obj.call('sql_get_purchase_need_result',[false, false]).then(function(){
                return self.do_search(self.last_domain, self.last_context, self.last_group_by);
            });
        },
        //重载列表数据
        do_search: function(domain, context, group_by) {
            var self = this;
            this.last_domain = domain;
            this.last_context = context;
            this.last_group_by = group_by;
            this.old_search = _.bind(this._super, this);
            return self.old_search(new instance.web.CompoundDomain(self.last_domain), self.last_context, self.last_group_by);
        },
    });

/* 这种方式刷新采购分录和时间，会导致默认展开的过滤和分组不会 默认展开
    instance.web.views.add('dftg_purchase_invoice_tree_js', 'instance.web.dftg_ext.PurchaseInvoiceView');
    instance.web.dftg_ext.PurchaseInvoiceView = instance.web.ListView.extend({
        init: function() {
            var self = this;
            this._super.apply(this, arguments);
            this.on('list_view_loaded', this, function() {
                if(self.__parentedParent.$el.find('.oe_purchase_invoice').length == 0){
                    var button1 = $("<button type='button' class='oe_button oe_purchase_invoice'>批量更新分录名称和时间</button>")
                        .click(this.proxy('do_refresh_action'));
                    self.__parentedParent.$el.find('.oe_list_buttons').append(button1);
                }
            });
        },
        do_refresh_action: function () {
            var self = this;
              var model=new instance.web.Model('official.invoice.lines');
                model.call("refresh_datetime_reconcile_account_name",[],{context:new instance.web.CompoundContext()}).then(function(){
                   self.reload();
                });
        },
    });*/


    instance.web_calendar.CalendarView.include({
         open_event: function(id, title) {
            var self = this;
            /*console.log(self,"id:",id,"title:",title,'model:',self.model);*/
            if (self.model=='crm.phonecall'){
                this.do_action({
                        type: 'ir.actions.act_window',
                        res_model: "crm.phonecall",
                        view_mode: 'tree',
                        view_type: 'tree,form',
                        views: [[false, 'list'],[false, 'form']],
                        domain:'[("previous_contact_id","=",'+id+')]',
                        target: 'current',
                        context:"{'default_previous_contact_id':"+id+"}",
                    }, {
                        on_reverse_breadcrumb: function () {
                            self.reload();
                        }
                    });
            }else{
                this._super.apply(this, arguments);
            }
         }

    });

    instance.web.form.FieldMobile = instance.web.form.FieldChar.extend({
        render_value: function() {
            this._super.apply(this, arguments);
            var input = this.$el.find('input');
            input.keyup(function(e) {
                var input_val =  input.val().replace(/^(\d)((\d)*)+/g,'1$2');
                if (input_val.length>11){
                    input_val = input_val.substring(0, 11)
                }
                input.val(input_val);
            })
        },
    });

    instance.web.form.widgets = instance.web.form.widgets.extend({
        'mobile' : 'instance.web.form.FieldMobile',
    });

    instance.dftg_ext.displayDeliveryPositionView = instance.web.Widget.extend({
        init: function() {
            this._super.apply(this, arguments);
        },

        start: function() {
            this._super.apply(this, arguments);
            var self = this;
            $.when($.get('/position/get_delivery_position_view')).done(function(result) {
                self.$el.append(result);
            });
        },
    });
    instance.web.client_actions.add('display_delivery_position_view', 'instance.dftg_ext.displayDeliveryPositionView');


    //接收消息通知（发送方式见bus.bus模块bus.py
    //浏览器 openerp.jsonRpc('/longpolling/send','call',{"channel":"c2","message":"m2"});
    instance.web.dftg_ext.Message = openerp.Widget.extend({
        init: function(parent, dashboard, options) {
            var self = this;
            this._super(parent);
            this.options = _.clone(options) || {};
            this.bus = openerp.bus.bus;
            //this.bus.last = 0;
            this.bus.channels = ['dftg_message'];
            this.bus.on("notification", this, this.on_notification);
            openerp.bus.bus.start_polling();
        },

        //消息通知处理函数
        on_notification: function(notification) {
            var self = this;
            var channel = notification[0];
            var message = notification[1];
            if (message.title && channel == 'dftg_message'){
                self.do_notify(message.title, message.content, true);
                $('.oe_notification.ui-notify').width('98%');
                this.window_beep();
            }
            else{
                console.log(message);
            }
        },
        window_beep: function() {
            if (typeof(Audio) === "undefined") {
                return;
            }
            var audio = new Audio();
            var ext = audio.canPlayType("audio/ogg; codecs=vorbis") ? ".ogg" : ".mp3";
            var kitten = jQuery.deparam !== undefined && jQuery.deparam(jQuery.param.querystring()).kitten !== undefined;
            audio.src = openerp.session.url("/dftg_ext/static/src/audio/" + (kitten ? "purr" : "ting") + ext);
            audio.play();
        },

    });

    if(openerp.web && openerp.web.UserMenu) {
        openerp.web.UserMenu.include({
            do_update: function(){
                var self = this;
                var dftg_manager = new openerp.web.dftg_ext.Message(this, this);
                return this._super.apply(this, arguments);
            },
        });
    }



    // ***************************************************************************************
    //
    //   扩展列表字段widget
    //
    //
    instance.web.dftg_ext.checked = function(){

    }
    instance.web.list.Column.include({
        _format: function(row_data, options) {
             if (this.widget === 'second_to_str'){
                 var all_hours = parseInt(row_data[this.id]['value']/3600);
                 var all_minus = parseInt(row_data[this.id]['value']/60);
                 return all_hours? (all_hours+"小时"+ all_minus+"分") :('' + all_minus+"分")
            }
            if (this.widget === 'purchase_need_sale_list') {
                var value = row_data[this.id]['value'];
                var so_list = JSON.parse(value);

                var html_list = [];
                for (var i = 0; i < so_list.length; i ++){
                    var so_item = so_list[i];
                    var number_color = 'blue';
                    if (so_item['change_qty'] < 0){
                        number_color = 'red'
                    }
                    var checked = '';
                    if (so_item['checked']){
                        checked = 'checked'
                    }

                    html_list.push(
                        _.str.sprintf('<label>%s<input type="checkbox" data-need_id="%s" data-so_id="%s" data-change_qty="%s" class="so-checkbox" %s/>%s,<span style="color:%s">%s</span></label></input>',
                            so_item['so_code'],
                            so_item['need_id'],
                            so_item['so_id'],
                            so_item['change_qty'],
                            checked,
                            so_item['date'], number_color,
                            so_item['change_text']
                            )
                    );
                    //console.log(so_item);
                }

                return html_list.join("<br/>");
                //return this._super(row_data, options);
            } else {
                return this._super(row_data, options);
            };


        },
    });

    instance.web.ListView.List.include({
        //处理采购需求表上的销售订单单击事件
        purchase_need_so_order_click: function(e){
            $target = $(e.target);
            var so_id = $target.data('so_id');
            var change_qty = $target.data('change_qty');
            var $td = $target.parent().parent();
            var $tr = $target.parent().parent().parent();
            var need_id = $tr.data('id');
            var $sale_change_qty_td = $tr.find('td[data-field=sale_change_qty]');
            var $purchase_need_qty_td = $tr.find('td[data-field=purchase_need_qty]');
            var non_delivery_qty = $tr.find('td[data-field=non_delivery_qty]').text() * 1;
            var available_qty = $tr.find('td[data-field=available_qty]').text() * 1;
            var inquiry_incoming_qty = $tr.find('td[data-field=inquiry_incoming_qty]').text() * 1;
            var purchase_incoming_qty = $tr.find('td[data-field=purchase_incoming_qty]').text() * 1;
            var checkbox_list = $td.find('input.so-checkbox');
            var so_ids = [];
            var sum_change_qty = 0;
            var sale_change_qty = false;
            for (var i = 0; i < checkbox_list.length; i ++){
                var $checkbox = $(checkbox_list[i]);
                var change_qty = $checkbox.data('change_qty') * 1;
                if ($checkbox.prop('checked')){
                    so_ids.push($checkbox.data('so_id'));
                    sale_change_qty += change_qty;
                }
                sum_change_qty += change_qty;
            }
            if (sale_change_qty === false){
                sale_change_qty = sum_change_qty;
            }
            //改变订单变更数
            $sale_change_qty_td.text(sale_change_qty);
            //改变采购需求量
            var purchase_need_qty = sale_change_qty + non_delivery_qty - available_qty
                - purchase_incoming_qty - inquiry_incoming_qty;
            $purchase_need_qty_td.text(purchase_need_qty);
            var model=new instance.web.Model('purchase.need');
            var so_ids_string = JSON.stringify(so_ids);
            if(so_ids_string=='[]') {
                so_ids_string=null
            }
            var checked_state = $target.prop('checked')
            model.call("write",[[need_id],{'choiced_so_ids':so_ids_string , 'sale_change_qty':sale_change_qty}],{context:new instance.web.CompoundContext()}).then(function(res){
                if(res.message=='error'){
                    $target.prop('checked',!checked_state)
                    alert("采购员"+res.user_name+"已经在处理这条记录!");
                }
            });
        },
        render: function() {
            var self = this;
            var result = this._super(this, arguments);
            this.$current.find('input.so-checkbox').click(function(e){
                self.purchase_need_so_order_click(e);
            });
            return result;
        },
    });

    instance.web.dftg_ext.FieldPurchaseNeedSaleList = openerp.web.list.Column.extend({});
    instance.web.dftg_ext.Fieldsecond_to_str = openerp.web.list.Column.extend({});
    instance.web.list.columns.add('field.purchase_need_sale_list', 'instance.web.dftg_ext.FieldPurchaseNeedSaleList');
    instance.web.list.columns.add('field.second_to_str', 'instance.web.dftg_ext.Fieldsecond_to_str');
  /*
    © 2015 NDP Systèmes (<http://www.ndp-systemes.fr>).
    © 2016 Savoir-faire Linux
    **
    * pivot 视图 字段的点击排序 (只支持一般的pivot视图的字段点击排序)
    License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
    */

    instance.web_graph.Graph.include({
        init: function(){
            this.events['click thead th.oe_sortable[data-id]'] = 'sort_by_column';
            this._super.apply(this, arguments);
        },
        draw_measure_row: function (measure_row) {
            var $row = $('<tr>').append('<th>');
            var self = this;
            var header_list = [];
            var title_string_list =_.map(measure_row,function (measure){return measure.string})
            var flag = _.every(_.map(self.measure_list,function (measure){
                var currcy_list =title_string_list;
                if(currcy_list.indexOf(measure.text)>=0 &&
                    currcy_list.splice(currcy_list.indexOf(measure.text)+1,currcy_list.length+1).indexOf(measure.text)<0 )
                {return true}else{return false}}));
            if(self.measure_list.length >= measure_row.length && flag){
                _.each(measure_row, function (cell, index) {
                    _.each(self.measure_list, function (item) {
                        if (item.field === self.pivot.measures[index].field && header_list.indexOf(item.field) < 0) {
                            header_list.push(item.field)
                            var data_id;
                            if (self.pivot.sort !== null &&
                                self.pivot.sort[0].indexOf(item.field) >= 0 &&
                                self.pivot.sort[0].indexOf('-') === -1
                            ) {
                                data_id = "-" + item.field;
                            }
                            else {
                                data_id = item.field;
                            }
                            var $cell = $('<th>')
                                .addClass('measure_row')
                                .addClass('oe_sortable')
                                .attr('data-id', data_id)
                                .append("<div>" + cell.text + "</div>");
                            if (cell.is_bold) {
                                $cell.css('font-weight', 'bold');
                            }
                            if (self.pivot.sort !== null && self.pivot.sort[0].indexOf(item.field) >= 0) {
                                $cell.addClass((self.pivot.sort[0].indexOf('-') === -1) ? "sortdown" : "sortup");
                            }
                            $row.append($cell);
                        }
                    });
                });

            }else{
                var $row = $('<tr>').append('<th>');
                _.each(measure_row, function (cell) {
                    var $cell = $('<th>').addClass('measure_row').text(cell.text);
                    if (cell.is_bold) {$cell.css('font-weight', 'bold');}
                    $row.append($cell);
                });
            }
            this.$thead.append($row);
        },
        /***
         *覆写原方法，对某些用户组隐藏这些字段
         */
        get_measures: function() {
            return _.compact(_.map(this.fields, function (f, id) {
                if (((f.type === 'integer') || (f.type === 'float')) &&
                    (id !== 'id') &&
                    (f.store !== false)&&f.invisible !== true) {
                    return {field:id, type: f.type, string: f.string};
                }
            }));
        },
        sort_by_column: function (e) {
            e.stopPropagation();
            var $column = $(e.currentTarget);
            var col_name = $column.data('id');
            this.pivot.sort = [col_name];
            this.pivot.update_data().then(this.proxy('display_data'));
        }
    });

    instance.web_graph.PivotTable.include({
        sort : null,
        get_groups: function (groupbys, fields, domain) {
            var self = this;
            var result = this.model.query(_.without(fields, '__count'));
            if(this.sort !== null) {
                result=result.order_by(this.sort);
            }
            return result.filter(domain)
                .context(this.context)
                .lazy(false)
                .group_by(groupbys)
                .then(function (groups) {
                    return groups.filter(function (group) {
                        return group.attributes.length > 0;
                    }).map(function (group) {
                        var attrs = group.attributes,
                            grouped_on = attrs.grouped_on instanceof Array ? attrs.grouped_on : [attrs.grouped_on],
                            raw_grouped_on = grouped_on.map(function (f) {
                                return self.raw_field(f);
                            });
                        if (grouped_on.length === 1) {
                            attrs.value = [attrs.value];
                        }
                        attrs.value = _.range(grouped_on.length).map(function (i) {
                            var grp = grouped_on[i],
                                field = self.fields[grp];

                            // This part was modified from original function in the web_graph module.
                            if (attrs.value[i] === false) {
                                return _t('Undefined');
                            } else if (attrs.value[i] instanceof Array) {
                                return attrs.value[i][1];
                            } else if (field && field.type === 'selection') {
                                var selected = _.where(field.selection, {0: attrs.value[i]})[0];
                                return selected ? selected[1] : attrs.value[i];
                            }
                            return attrs.value[i];
                        });
                        attrs.aggregates.__count = group.attributes.length;
                        attrs.grouped_on = raw_grouped_on;
                        return group;
                    });
                });
        }
    });
};